<template>
  <div class="category-detail">
    <div class="category-info">
      <h1>{{ category.name }}</h1>
      <p class="description">{{ category.description }}</p>
    </div>

    <div class="products-container">
      <h2>分类商品</h2>
      <el-row :gutter="20">
        <el-col
          v-for="product in products"
          :key="product.id"
          :xs="24"
          :sm="12"
          :md="8"
          :lg="6"
          :xl="4"
        >
          <el-card
            class="product-card"
            shadow="hover"
            @click="viewProductDetail(product.id)"
          >
            <img :src="product.image" class="product-image" />
            <div class="product-info">
              <h3>{{ product.name }}</h3>
              <p class="price">¥{{ product.price }}</p>
              <p class="location">
                <el-icon><Location /></el-icon>
                {{ product.location }}
              </p>
            </div>
          </el-card>
        </el-col>
      </el-row>

      <div class="pagination">
        <el-pagination
          v-model:current-page="currentPage"
          v-model:page-size="pageSize"
          :total="total"
          :page-sizes="[12, 24, 36, 48]"
          layout="total, sizes, prev, pager, next"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        />
      </div>
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref, onMounted } from 'vue'
import { useRoute, useRouter } from 'vue-router'
import { Location } from '@element-plus/icons-vue'
import { ElMessage } from 'element-plus'

const route = useRoute()
const router = useRouter()
const categoryId = route.params.id

// 分类信息
const category = ref({
  id: '',
  name: '',
  description: ''
})

// 商品列表
const products = ref([])
const currentPage = ref(1)
const pageSize = ref(12)
const total = ref(0)

// 获取分类信息
const fetchCategoryInfo = async () => {
  try {
    // TODO: 替换为实际的API调用
    category.value = {
      id: categoryId as string,
      name: '示例分类',
      description: '这是一个示例分类的详细描述'
    }
  } catch (error) {
    ElMessage.error('获取分类信息失败')
  }
}

// 获取分类商品
const fetchCategoryProducts = async () => {
  try {
    // TODO: 替换为实际的API调用
    products.value = Array(12).fill(null).map((_, index) => ({
      id: `${index + 1}`,
      name: `商品 ${index + 1}`,
      price: Math.floor(Math.random() * 1000) + 10,
      image: `https://picsum.photos/300/200?random=${index}`,
      location: '示例位置'
    }))
    total.value = 100
  } catch (error) {
    ElMessage.error('获取商品列表失败')
  }
}

// 查看商品详情
const viewProductDetail = (productId: string) => {
  router.push(`/product/${productId}`)
}

// 分页处理
const handleSizeChange = (val: number) => {
  pageSize.value = val
  fetchCategoryProducts()
}

const handleCurrentChange = (val: number) => {
  currentPage.value = val
  fetchCategoryProducts()
}

onMounted(() => {
  fetchCategoryInfo()
  fetchCategoryProducts()
})
</script>

<style scoped>
    <div class="category-header">
      <div class="category-info">
        <el-icon class="category-icon" :size="32"><component :is="categoryIcon" /></el-icon>
        <h2 class="category-title">{{ categoryData.name }}</h2>
        <div class="category-count">{{ categoryData.count }} 件商品</div>
      </div>
      <div class="filter-actions">
        <el-select v-model="sortBy" placeholder="排序方式" class="filter-select">
          <el-option label="最新发布" value="newest"></el-option>
          <el-option label="价格从低到高" value="price_asc"></el-option>
          <el-option label="价格从高到低" value="price_desc"></el-option>
          <el-option label="最受欢迎" value="popular"></el-option>
        </el-select>
        <el-button-group class="view-mode">
          <el-button :type="viewMode === 'grid' ? 'primary' : ''" @click="viewMode = 'grid'">
            <el-icon><Grid /></el-icon>
          </el-button>
          <el-button :type="viewMode === 'list' ? 'primary' : ''" @click="viewMode = 'list'">
            <el-icon><List /></el-icon>
          </el-button>
        </el-button-group>
      </div>
    </div>

    <div class="category-content">
      <div class="filter-sidebar">
        <el-card class="filter-card">
          <template #header>
            <div class="filter-header">
              <span>筛选条件</span>
              <el-button link @click="resetFilters">重置</el-button>
            </div>
          </template>
          
          <div class="filter-section">
            <h4>价格区间</h4>
            <div class="price-range">
              <el-input-number v-model="priceRange.min" :min="0" :step="10" placeholder="最低价"></el-input-number>
              <span class="separator">-</span>
              <el-input-number v-model="priceRange.max" :min="0" :step="10" placeholder="最高价"></el-input-number>
            </div>
          </div>
          
          <div class="filter-section">
            <h4>商品状态</h4>
            <el-checkbox-group v-model="selectedCondition">
              <el-checkbox label="全新">全新</el-checkbox>
              <el-checkbox label="几乎全新">几乎全新</el-checkbox>
              <el-checkbox label="轻微使用">轻微使用</el-checkbox>
              <el-checkbox label="正常使用">正常使用</el-checkbox>
            </el-checkbox-group>
          </div>
          
          <div class="filter-section">
            <h4>学校</h4>
            <el-checkbox-group v-model="selectedSchools">
              <el-checkbox v-for="school in schoolOptions" :key="school.id" :label="school.id">
                {{ school.name }}
              </el-checkbox>
            </el-checkbox-group>
          </div>
          
          <el-button type="primary" class="apply-filter-btn" @click="applyFilters">应用筛选</el-button>
        </el-card>
      </div>
      
      <div class="products-container">
        <div v-if="loading" class="loading-container">
          <el-skeleton :rows="5" animated />
          <el-skeleton :rows="5" animated />
          <el-skeleton :rows="5" animated />
        </div>
        
        <div v-else-if="products.length === 0" class="empty-results">
          <el-empty description="没有符合条件的商品" />
        </div>
        
        <div v-else :class="['products-grid', { 'list-view': viewMode === 'list' }]">
          <el-card 
            v-for="product in products" 
            :key="product.id" 
            :body-style="{ padding: '0' }"
            class="product-card"
            shadow="hover"
            @click="goToProduct(product.id)"
          >
            <div class="product-image-container">
              <el-image :src="product.image" fit="cover" class="product-image" />
              <div v-if="product.isHot" class="product-badge hot">热门</div>
              <div v-if="product.isNew" class="product-badge new">新品</div>
            </div>
            <div class="product-info">
              <h3 class="product-title">{{ product.name }}</h3>
              <div class="product-meta">
                <span class="product-school">{{ product.school }}</span>
                <span class="product-condition">{{ product.condition }}</span>
              </div>
              <div class="product-footer">
                <div class="product-price">¥{{ product.price }}</div>
                <div class="product-actions">
                  <el-button size="small" circle><el-icon><StarFilled /></el-icon></el-button>
                  <el-button size="small" circle><el-icon><Message /></el-icon></el-button>
                </div>
              </div>
            </div>
          </el-card>
        </div>
        
        <div class="pagination-container">
          <el-pagination
            v-model:current-page="currentPage"
            v-model:page-size="pageSize"
            :page-sizes="[12, 24, 36, 48]"
            layout="total, sizes, prev, pager, next, jumper"
            :total="totalProducts"
            @size-change="handleSizeChange"
            @current-change="handleCurrentChange"
          />
        </div>
      </div>
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref, computed, onMounted } from 'vue';
import { useRoute, useRouter } from 'vue-router';
import { 
  Grid, List, StarFilled, Message, 
  Reading, ShoppingBag, Suitcase, Football, Camera, Iphone 
} from '@element-plus/icons-vue';
import { ElMessage } from 'element-plus';

const route = useRoute();
const router = useRouter();
const categoryId = computed(() => route.params.id);

// 类别数据
const categoryData = ref({
  id: categoryId,
  name: '加载中...',
  count: 0,
  description: ''
});

// 图标映射
const iconMap = {
  1: 'Iphone',      // 数码产品
  2: 'Reading',     // 图书教材
  3: 'Suitcase',    // 生活用品
  4: 'ShoppingBag', // 服装鞋包
  5: 'Football'     // 体育用品
};

const categoryIcon = computed(() => {
  return iconMap[categoryId.value] || 'Suitcase';
});

// 筛选和排序状态
const viewMode = ref('grid');
const sortBy = ref('newest');
const priceRange = ref({ min: null, max: null });
const selectedCondition = ref([]);
const selectedSchools = ref([]);

// 分页
const currentPage = ref(1);
const pageSize = ref(12);
const totalProducts = ref(0);

// 产品和加载状态
const products = ref([]);
const loading = ref(true);

// 学校选项
const schoolOptions = ref([
  { id: 1, name: '北京大学' },
  { id: 2, name: '清华大学' },
  { id: 3, name: '中国人民大学' },
  { id: 4, name: '北京师范大学' },
  { id: 5, name: '北京航空航天大学' }
]);

// 加载类别数据
const loadCategoryData = async () => {
  loading.value = true;
  
  try {
    // 模拟API调用 - 实际应用中替换为真实API
    await new Promise(resolve => setTimeout(resolve, 500));
    
    // 模拟数据 - 根据categoryId设置
    const categories = {
      1: { name: '数码产品', count: 568, description: '各类电子产品、手机、电脑、相机等' },
      2: { name: '图书教材', count: 732, description: '各类教材、课外读物、考试资料等' },
      3: { name: '生活用品', count: 421, description: '日常生活用品、宿舍用品等' },
      4: { name: '服装鞋包', count: 389, description: '各类服装、鞋子、箱包等' },
      5: { name: '体育用品', count: 245, description: '运动器材、健身装备等' }
    };
    
    categoryData.value = categories[categoryId.value] || { 
      name: '未知分类', 
      count: 0, 
      description: '该分类不存在'
    };
    
    // 设置总商品数
    totalProducts.value = categoryData.value.count;
    
    // 加载商品
    await loadProducts();
  } catch (error) {
    console.error('加载分类数据出错:', error);
  } finally {
    loading.value = false;
  }
};

// 加载商品数据
const loadProducts = async () => {
  loading.value = true;
  
  try {
    // 模拟API调用 - 实际应用中替换为真实API
    await new Promise(resolve => setTimeout(resolve, 600));
    
    // 模拟商品数据
    const mockProducts = [];
    const conditions = ['全新', '几乎全新', '轻微使用', '正常使用'];
    const schools = schoolOptions.value.map(school => school.name);
    
    // 生成模拟数据
    for (let i = 1; i <= pageSize.value; i++) {
      const id = (currentPage.value - 1) * pageSize.value + i;
      mockProducts.push({
        id,
        name: `${categoryData.value.name}商品 ${id}`,
        price: Math.floor(Math.random() * 1000) + 50,
        image: '/src/assets/placeholder.png',
        school: schools[Math.floor(Math.random() * schools.length)],
        condition: conditions[Math.floor(Math.random() * conditions.length)],
        isHot: Math.random() > 0.8,
        isNew: Math.random() > 0.7
      });
    }
    
    products.value = mockProducts;
  } catch (error) {
    console.error('加载商品数据出错:', error);
  } finally {
    loading.value = false;
  }
};

// 重置筛选条件
const resetFilters = () => {
  priceRange.value = { min: null, max: null };
  selectedCondition.value = [];
  selectedSchools.value = [];
};

// 应用筛选条件
const applyFilters = async () => {
  currentPage.value = 1;
  await loadProducts();
};

// 处理分页大小变化
const handleSizeChange = async (size) => {
  pageSize.value = size;
  await loadProducts();
};

// 处理页码变化
const handleCurrentChange = async (page) => {
  currentPage.value = page;
  await loadProducts();
};

// 跳转到商品详情
const goToProduct = (productId: string | number) => {
  router.push(`/product/${productId}`)
}

// 当组件挂载时加载数据
onMounted(() => {
  loadCategoryData();
});
</script>

<style scoped>
.category-detail {
  max-width: 1200px;
  margin: 0 auto;
  padding: 20px;
}

.category-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
  padding-bottom: 20px;
  border-bottom: 1px solid #eee;
}

.category-info {
  display: flex;
  align-items: center;
  gap: 12px;
}

.category-icon {
  color: #409eff;
}

.category-title {
  margin: 0;
  font-size: 24px;
  font-weight: 600;
}

.category-count {
  color: #909399;
  font-size: 14px;
}

.filter-actions {
  display: flex;
  gap: 12px;
}

.filter-select {
  width: 160px;
}

.category-content {
  display: flex;
  gap: 20px;
}

.filter-sidebar {
  width: 240px;
  flex-shrink: 0;
}

.filter-card {
  position: sticky;
  top: 80px;
}

.filter-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.filter-section {
  margin-bottom: 20px;
}

.filter-section h4 {
  margin: 0 0 10px;
  font-size: 16px;
  font-weight: 500;
}

.price-range {
  display: flex;
  align-items: center;
  gap: 8px;
}

.price-range .el-input-number {
  width: 100px;
}

.separator {
  color: #909399;
}

.apply-filter-btn {
  width: 100%;
  margin-top: 10px;
}

.products-container {
  flex: 1;
  min-width: 0;
}

.loading-container {
  margin-bottom: 20px;
}

.empty-results {
  padding: 40px 0;
  text-align: center;
}

.products-grid {
  display: grid;
  grid-template-columns: repeat(auto-fill, minmax(220px, 1fr));
  gap: 20px;
}

.products-grid.list-view {
  grid-template-columns: 1fr;
}

.product-card {
  cursor: pointer;
  transition: transform 0.3s;
}

.product-card:hover {
  transform: translateY(-5px);
}

.product-image-container {
  position: relative;
  height: 200px;
}

.list-view .product-image-container {
  height: 150px;
  width: 150px;
  float: left;
}

.product-image {
  width: 100%;
  height: 100%;
  object-fit: cover;
}

.product-badge {
  position: absolute;
  top: 10px;
  left: 10px;
  padding: 4px 10px;
  border-radius: 4px;
  font-size: 12px;
  font-weight: 500;
  color: white;
}

.product-badge.hot {
  background-color: #f56c6c;
}

.product-badge.new {
  background-color: #67c23a;
}

.product-info {
  padding: 15px;
}

.list-view .product-info {
  margin-left: 170px;
  min-height: 150px;
}

.product-title {
  margin: 0 0 10px;
  font-size: 16px;
  font-weight: 500;
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
}

.product-meta {
  display: flex;
  justify-content: space-between;
  margin-bottom: 15px;
  font-size: 14px;
  color: #909399;
}

.product-footer {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.product-price {
  font-size: 20px;
  font-weight: 600;
  color: #f56c6c;
}

.product-actions {
  display: flex;
  gap: 5px;
}

.pagination-container {
  margin-top: 30px;
  display: flex;
  justify-content: center;
}

@media (max-width: 768px) {
  .category-content {
    flex-direction: column;
  }
  
  .filter-sidebar {
    width: 100%;
    margin-bottom: 20px;
  }
  
  .products-grid {
    grid-template-columns: repeat(auto-fill, minmax(160px, 1fr));
  }
}
</style> 